﻿Imports System
Imports System.ComponentModel
Imports System.Reflection
Imports System.Workflow.ComponentModel

Namespace System.Workflow.ComponentModel.Design
    Friend Class TypePropertyDescriptor
        Inherits DynamicPropertyDescriptor
        ' Methods
        Public Sub New(ByVal serviceProvider As IServiceProvider, ByVal actualPropDesc As PropertyDescriptor)
            MyBase.New(serviceProvider, actualPropDesc)
        End Sub

        Public Overrides Function GetValue(ByVal component As Object) As Object
            If (component Is Nothing) Then
                Throw New ArgumentNullException("component")
            End If
            Dim designTimeTypeName As Object = MyBase.GetValue(component)
            If (designTimeTypeName Is Nothing) Then
                Dim owner As DependencyObject = [TryCast](component,DependencyObject)
                If (Not owner Is Nothing) Then
                    Dim key As Object = DependencyProperty.FromName(MyBase.RealPropertyDescriptor.Name, MyBase.RealPropertyDescriptor.ComponentType)
                    designTimeTypeName = Helpers.GetDesignTimeTypeName(owner, key)
                    If String.IsNullOrEmpty([TryCast](designTimeTypeName,String)) Then
                        key = (MyBase.RealPropertyDescriptor.ComponentType.FullName & "." & MyBase.RealPropertyDescriptor.Name)
                        designTimeTypeName = Helpers.GetDesignTimeTypeName(owner, key)
                    End If
                End If
            End If
            Return designTimeTypeName
        End Function

        Public Overrides Sub SetValue(ByVal component As Object, ByVal value As Object)
            If (component Is Nothing) Then
                Throw New ArgumentNullException("component")
            End If
            If (Not value Is Nothing) Then
                Dim type As Type = [TryCast](value,Type)
                Dim provider As ITypeFilterProvider = [TryCast](PropertyDescriptorUtils.GetComponent(New TypeDescriptorContext(MyBase.ServiceProvider, MyBase.RealPropertyDescriptor, component)),ITypeFilterProvider)
                If (Not provider Is Nothing) Then
                    provider.CanFilterType(type, True)
                End If
            End If
            MyBase.SetValue(component, value)
        End Sub


        ' Properties
        Public Overrides ReadOnly Property Converter As TypeConverter
            Get
                Dim converter As TypeConverter = MyBase.Converter
                Dim fullName As String = converter.GetType.FullName
                Dim c As Type = Assembly.GetExecutingAssembly.GetType(fullName)
                If ((Not c Is Nothing) AndAlso GetType(TypePropertyTypeConverter).IsAssignableFrom(c)) Then
                    Return converter
                End If
                Return New TypePropertyTypeConverter
            End Get
        End Property

    End Class
End Namespace

